﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace Toenda.Foundation {
	/// <summary>
	/// Implements a class to read settings from the App.Config file
	/// </summary>
	public static class AppSettings {
		private static AppSettingsReader _reader = new AppSettingsReader();

		/// <summary>
		/// Get a value from the App.Config file, if the key dos'nt exist or is empty, it returns an empty string
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public static string GetAppConfigValue(string key) {
			return GetAppConfigValue(key, "");
		}

		/// <summary>
		/// Get a value from the App.Config file, if the key dos'nt exist or is empty, it returns the alternative value
		/// </summary>
		/// <param name="key"></param>
		/// <param name="alternativeValue"></param>
		/// <returns></returns>
		public static string GetAppConfigValue(string key, string alternativeValue) {
			try {
				string setting = ConfigurationManager.AppSettings[key];

				if(string.IsNullOrEmpty(setting)) {
					return alternativeValue;
				}
				else {
					return setting;
				}
			}
			catch(Exception) {
				return alternativeValue;
			}
		}

		/// <summary>
		/// Get a value from the App.Config file, if the key dos'nt exist or is empty, it returns the alternative value
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="key"></param>
		/// <param name="alternativeValue"></param>
		/// <returns></returns>
		public static T GetAppConfigValue<T>(string key, T alternativeValue) {
			try {
				//string setting = ConfigurationManager.AppSettings[key];
				T setting = _reader.GetValue(key, typeof(string)).ToString().ToType<T>();

				if(setting == null || ( setting is string && ( setting.ToString() ).IsNullOrTrimmedEmpty() )) {
					return alternativeValue;
				}
				else {
					return setting;
				}
			}
			catch(InvalidOperationException) {
				return alternativeValue;
			}
			catch(Exception) {
				return alternativeValue;
			}
		}
	}
}
